#include <stdio.h>
#include <uv.h>

void wake_entry(void *arg) 
{
    uv_sleep(1000);
    printf("uv_thread id: %d, wake async!\n", (int)uv_thread_self());
    uv_async_send((uv_async_t*)arg);
}

void my_async_cb(uv_async_t* handle)
{
    printf("uv_thread id: %d, my_async_cb!\n", (int)uv_thread_self());
    // uv_unref((uv_handle_t *)handle);   --------- mem leak
    // uv_loop_close(handle->loop);       --------- mem leak
    uv_close((uv_handle_t *)handle, NULL);
}

void periodic_job(uv_timer_t* handle) {
    static int i = 0;
    printf("periodic timer : %d !!!\n", ++ i);
    if(i >= 5)
    {
        uv_timer_stop(handle);
        uv_close((uv_handle_t *)handle, NULL);
    }
}

int main() 
{

    printf("begin!\n");
    uv_loop_t *loop = uv_default_loop();
    uv_timer_t time_req;
    uv_timer_init(loop, &time_req);
    uv_timer_start(&time_req, periodic_job, 0, 1000);

    printf("uv_thread id: %d, main!\n", (int)uv_thread_self());
    uv_thread_t wake;
    uv_async_t async;
    uv_async_init(loop, &async, my_async_cb);
    uv_thread_create(&wake, wake_entry, &async);

    uv_run(loop, UV_RUN_DEFAULT);
    uv_loop_close(loop);
    uv_thread_join(&wake);

    printf("end!\n");
    return 0;
}
